<template>
  <div class="app-container" >
    <el-container style="height:100%;">
      <el-header style="height:auto;padding:10px;">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="productCategoryId">
        <el-cascader :options="prodCateTreeList" :show-all-levels="false"
         v-model="queryParams.productCategoryId" @change="handleChange1"></el-cascader>
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandName">
        <el-input
          v-model="queryParams.brandName"
          placeholder="请输入品牌名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mall:product:edit']"
        >修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mall:product:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mall:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    </el-header>
      <el-main style="padding:0;">
        <el-table ref="table" style="width: 100%;"  v-loading="loading" :data="productList"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
                  <el-table-column label="主图" align="center" prop="picture" width="100">
                    <template slot-scope="scope">
                      <image-preview :src="scope.row.picture" :width="50" :height="50"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="商品名称" align="center" prop="productName"/>
                  <el-table-column label="商品分类" align="center" prop="productCategoryName"/>
                  <el-table-column label="品牌名称" align="center" prop="brandName"/>
                  <el-table-column label="市场价" align="center" prop="originalPrice"/>
                  <el-table-column label="销售价格" align="center" prop="sellPrice"/>
                  <el-table-column label="上架状态" align="center" prop="publishStatus">
                    <template slot-scope="scope">
                      <el-switch
                        :active-value="1"
                        :inactive-value="0"
                        v-model="scope.row.publishStatus"
                        @change="handleStatusChange( scope.row,'publish')">
                      </el-switch>
                    </template>
                  </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['mall:product:edit']"
              >修改
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['mall:product:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer style="border-top:1px solid #ccc;height:auto;padding:10px;">
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
      </el-footer>
    </el-container>

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" v-if="open" :model="form" :rules="rules" label-width="80px">

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>商品信息</span>
          </div>
          <div class="text item">
              <el-row>
                <el-col :span="16">
                  <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="form.productName" placeholder="请输入商品名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="商品分类" prop="productCategoryId">
                    <el-cascader :options="prodCateTreeList" :show-all-levels="false"
                      v-model="form.productCategoryId" @change="handleChange2"></el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="品牌名称" prop="brandName">
                    <el-input v-model="form.brandName" placeholder="请输入品牌名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="市场价" prop="originalPrice">
                    <el-input-number v-model="form.originalPrice" :precision="2" :step="1"  placeholder="请输入市场价"></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="销售价格" prop="sellPrice">
                    <el-input-number v-model="form.sellPrice" :precision="2" :step="1"  placeholder="请输入销售价格"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="单位" prop="unit">
                    <el-input v-model="form.unit" placeholder="请输入单位" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="产地" prop="producingArea">
                    <el-input v-model="form.producingArea" placeholder="请输入产地" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="储存方式" prop="storageMethod">
                    <el-input v-model="form.storageMethod" placeholder="请输入储存方式" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="商品简介" prop="description">
                    <el-input v-model="form.description"  placeholder="请输入商品简介"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="商品规格" prop="specs">
                    <el-input v-model="form.specs"  placeholder="请输入商品规格"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="form.sort"  :step="1"  placeholder="请输入排序"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="vip1价格" prop="vip1">
                    <el-input v-model="form.vip1"  placeholder="请输入vip1价格"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="vip2价格" prop="vip2">
                    <el-input v-model="form.vip2"  placeholder="请输入vip2价格"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="vip3价格" prop="vip3">
                    <el-input v-model="form.vip3"  placeholder="请输入vip3价格"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

          </div>
        </el-card>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>商品图片</span>
          </div>
          <div class="text item">
            <el-form-item label="主图" prop="picture">
              <image-upload :limit="1" v-model="form.picture" />
            </el-form-item>
            <el-form-item label="轮播图" prop="albumPics">
              <image-upload :limit="5" v-model="form.albumPics"/>
            </el-form-item>
            <el-form-item label="详情图" prop="detailPicture">
              <image-upload :limit="5" v-model="form.detailPicture"/>
            </el-form-item>
          </div>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>多种规格</span>
          </div>
          <div class="text item">
            <el-row>
              <el-col :span="3" ><div style="font-size: 14px;font-weight: bold;text-align: right;margin: 16px;">  规格类型</div></el-col>
              <el-col :span="21">
                <div class="sku_sorts">
                  <div class="sku_sort" v-for="(keyitem,keyindex) in specsKeyList" :key="keyindex" :value="keyitem" :label="keyitem">
                    <div class="sku_content">
                      <el-select v-model="specsKeyList[keyindex].attrType" placeholder="请选择">
                          <el-option
                            v-for="item in productAttributeTypeList"
                            :key="item.typename"
                            :label="item.typename"
                            :value="item.typename">
                          </el-option>
                      </el-select>
                      <el-button type="text" style="color: lightcoral;float: right;" @click="delAttrKey(keyindex)">删除规格类型</el-button>
                      <div class="sku_values">
                        <span v-for="(item,index) in specsKeyList[keyindex].attrValue" :key="index" :value="index" :label="item">
                          <el-input style="width: 20%;" v-model="specsKeyList[keyindex].attrValue[index]"></el-input>
                          <el-button type="text" style="color: lightcoral;margin:0 20px 20px 0;" @click="delAttrValue(keyindex,index)">删除</el-button>
                        </span>
                        <i class="el-icon-circle-plus-outline" style="font-size: 20px;cursor: pointer;" @click="addAttrValue(keyindex)"></i>
                      </div>

                    </div>

                  </div>
                  <div class="sku_empty" v-show="specsKeyList.length<2">
                    <el-button style="margin: 16px 20px;" @click="addAttrKey">+添加规格类型</el-button>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>

          <div class="text item" style="margin-top: 16px;">
            <el-row>
              <el-col :span="3" ><div style="font-size: 14px;font-weight: bold;text-align: right;margin: 16px;">  规格信息</div></el-col>
              <el-col :span="21">
                <el-button @click="getSkuData">刷新列表</el-button>
                <el-table :data="skuDataList" stripe style="width: 100%">
                    <el-table-column prop="specs1" :label="skuHeadData[0]" v-if="skuHeadData.length>=1" > </el-table-column>
                    <el-table-column prop="specs2" :label="skuHeadData[1]" v-if="skuHeadData.length==2"> </el-table-column>
                    <el-table-column prop="originalPrice" label="市场价格" >
                      <template slot-scope="scope">
                        <el-input v-model="skuDataList[scope.$index].originalPrice"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="sellPrice" label="销售价格" >
                      <template slot-scope="scope">
                        <el-input v-model="skuDataList[scope.$index].sellPrice"></el-input>
                      </template>
                    </el-table-column>

                  </el-table>

              </el-col>
            </el-row>
          </div>

        </el-card>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/mall/product";
import { listProdCate, getProdCateTreeList } from "@/api/mall/prodCate";
import { listProductAttributeType } from "@/api/mall/productAttributeType";
import { getProductSpecs,updateProductSpecs } from "@/api/mall/productAttributeSku";

export default {
  name: "Product",
  data() {
    return {
      mainHeight: '100px',//表格默认高度
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      productList: [],
      // 商品规格类别数据
      productAttributeTypeList: [],
      skuHeadData:[],
      // 商品分类
      prodCateTreeList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 规格类型列表
      specsKeyList:[],// [{attrType:'',attrValue:[]}]
      // 规格数据
      skuDataList:[], // [{specs1:'红',specs2:'',originalPrice:36.5,sellPrice:44.2}]
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productCategoryId: null,
        brandName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          {required: true, message: '请输入商品名称', trigger: 'blur'},
        ],
        originalPrice: [
          {required: true, message: '请输入市场价格', trigger: 'blur'},
        ],
        sellPrice: [
          {required: true, message: '请输入销售价格', trigger: 'blur'},
        ],
        productCategoryId: [
          {required: true, message: '请选择商品分类', trigger: 'change'},
        ],
      }
    };
  },
  mounted() {
    //此处动态计算窗口变化
    this.mainHeight = document.documentElement.clientHeight - 85 + 'px'
    const that = this
    window.onresize = function temp() {
      that.mainHeight = document.documentElement.clientHeight - 85 + 'px'
    }
  },
  created() {
    this.getList();
    this.getProdCateList();
    this.getAttributeTypeList();
  },
  methods: {
    /** 查询商品信息列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询商品分类列表 */
    getProdCateList() {
      getProdCateTreeList().then(response => {
        this.prodCateTreeList = response.rows;
      });
    },
    /** 查询商品规格类别列表 */
    getAttributeTypeList() {
      let queryParams = {
        pageNum: 1,
        pageSize: 9999
      }
      listProductAttributeType(queryParams).then(response => {
        this.productAttributeTypeList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productName: null,
        productCategoryId: null,
        productCategoryName: null,
        brandName: null,
        originalPrice: null,
        sellPrice: null,
        unit: null,
        weight: null,
        producingArea: null,
        storageMethod: null,
        description: null,
        specs: null,
        picture: null,
        albumPics: null,
        detailPicture: null,
        sort: null,
        createBy: null,
        createTime: null,
        deleteStatus: null,
        publishStatus: null,
        vip1: null,
        vip2: null,
        vip3: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.specsKeyList = [];
      this.skuDataList = [];
      // 默认值
      this.form.sort = 1;
      this.form.storageMethod = "常温";
      this.open = true;
      this.title = "添加商品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品信息";
      });
      this.queryProductSpecsByProductId(id)
    },
    //修改商品上架状态
    handleStatusChange(row, type) {
      let data = {
        id: row.id,
        publishStatus:row.publishStatus
      }
      updateProduct(data).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        });
      }).catch(error => {
        data.publishStatus = data.publishStatus ==0 ? 1:0
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.updateSpecs();
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.updateSpecs();
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });

    },
    // 商品更新规格信息
    updateSpecs(){
      let data = {
        productId:this.form.id,
        specsKeyList:this.specsKeyList,
        skuDataList:this.skuDataList
      }
      updateProductSpecs(data).then(response => {

      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      let data = {
        id: ids,
        deleteStatus:1
      }
      this.$modal.confirm('是否确认删除商品信息编号为"' + ids + '"的数据项？').then(function() {
        return updateProduct(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mall/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
    handleChange1(value) {
      this.queryParams.productCategoryId = value[value.length-1];
        // console.log(value+"---长度："+value.length+"---值："+value[value.length-1]);
    },
    handleChange2(value) {
      this.form.productCategoryId = value[value.length-1];
    },
    delAttrValue(keyindex,index){
      this.specsKeyList[keyindex].attrValue.splice(index,1)
    },
    addAttrValue(keyindex){
      this.specsKeyList[keyindex].attrValue.push('')
    },
    addAttrKey(){
      let obj = {attrType:'',attrValue:[]}
      this.specsKeyList.push(obj)
    },
    delAttrKey(keyindex){
      this.specsKeyList.splice(keyindex,1);
    },
    getSkuData(){
      let skuHeadData = [];
      let arr = []

      let specsValArr1 = []
      let specsValArr2 = []
      if(this.specsKeyList.length==2){
        skuHeadData.push(this.specsKeyList[0].attrType)
        skuHeadData.push(this.specsKeyList[1].attrType)
        specsValArr1 = this.specsKeyList[0].attrValue
        specsValArr2 = this.specsKeyList[1].attrValue

        for(let i of specsValArr1){
          for(let j of specsValArr2){
            let item = {
              originalPrice:this.form.originalPrice,
              sellPrice:this.form.sellPrice,
              specs1:i,
              specs2:j
            }
            arr.push(item)
          }
        }

      }else if(this.specsKeyList.length==1){
        skuHeadData.push(this.specsKeyList[0].attrType)
        specsValArr1 = this.specsKeyList[0].attrValue

        for(let i of specsValArr1){
          let item = {
            originalPrice:this.form.originalPrice,
            sellPrice:this.form.sellPrice,
            specs1:i
          }
          arr.push(item)
        }


      }

      this.skuDataList = arr
      this.skuHeadData = skuHeadData
    },
    queryProductSpecsByProductId(id){
      // 规格回显
      getProductSpecs({productId:id}).then(response => {
        // console.log(response)
        this.specsKeyList = response.data.specsKeyList;
        this.skuDataList = response.data.skuDataList;
        for(let obj of this.specsKeyList){
          this.skuHeadData.push(obj.attrType)
        }
      });
    },
  }
};
</script>
<style>
  .box-card{margin: 16px 0;}
  .sku_sorts{background:#F8F8F9;padding: 10px;}
  .sku_sort{margin-bottom: 10px;}
  .sku_content{background:white;padding: 10px;}
  .sku_values{border-top: 2px solid #F8F8F9;margin-top: 10px;padding-top: 10px;}
</style>
